package com.nativetalk.service.teacher.login;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.TdNtTeacher;
import com.nativetalk.bean.rongyun.RongCloudConfig;
import com.nativetalk.bean.rongyun.TokenResult;
import com.nativetalk.bean.teacher.TdNtTeacherLogin;
import com.nativetalk.bean.teacher.TdNtTeacherResult;
import com.nativetalk.bean.teacher.TdNtTeacherState;
import com.nativetalk.bean.user.TdNtUserLoginLog;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.rongCloud.RongCloud;
import com.nativetalk.common.util.CommonUtil;
import com.nativetalk.common.util.MD5;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.dao.TdNtTeacherDao;
import com.nativetalk.dao.TdNtUserLoginLogDao;
import com.tls.tls_sigature.tls_sigature;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lizhun on 16/1/8.
 */
@Service
public class TeacherLoginServiceImpl implements TeacherLoginService {
    private static Logger logger = Logger.getLogger(TeacherLoginServiceImpl.class);
    private static String WAIJIAOJUN_URL = "file.waijiaojun.com/";

    @Resource
    private TdNtTeacherDao tdNtTeacherDao;
    @Resource
    private TdNtUserLoginLogDao tdNtUserLoginLogDao;
    @Resource
    private RongCloudConfig rongCloudConfig;

    @Override
    public RetInfo login(TdNtTeacherLogin tdNtTeacherLogin, int version) {
        String logInfo = this.getClass().getName() + ":login:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {

            TdNtTeacherResult tdNtTeacherResult = tdNtTeacherDao.findTdNtTeacherResult(tdNtTeacherLogin.getTea_email());
            if (tdNtTeacherResult != null) {
                if (tdNtTeacherResult.getTea_password().equals(MD5.code(tdNtTeacherLogin.getTea_password()))) {
                    if (!tdNtTeacherResult.getTea_islock().equals("0")) {
                        String token = tdNtTeacherResult.getToken();
                        tdNtTeacherResult.setToken(CommonUtil.getToken());
                        tdNtTeacherResult.setEqu_type(tdNtTeacherLogin.getEqu_type());
                        tdNtTeacherResult.setEqu_client_id(tdNtTeacherLogin.getEqu_client_id());

                        tdNtTeacherDao.updateTdNtTeacherPsdAndToken(tdNtTeacherResult);
                        MemcachedUtils.add(tdNtTeacherResult.getToken(), tdNtTeacherResult, 20 * 24 * 60 * 60);
                        MemcachedUtils.delete(token);

                        retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                        retInfo.setTip(ValidationMessages.getValue("TEACHER.LOGIN.SUCCESS"));
                        retInfo.setObj(tdNtTeacherResult.getToken());
                    } else {
                        retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                        retInfo.setTip(ValidationMessages.getValue("TEACHER.LOGIN.LOCK"));
                    }

                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("TEACHER.PSD.ERROR"));
                }

            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("TEACHER.LOGIN.NULL"));
            }
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    @Transactional
    public RetInfo out(TdNtTeacherResult tdNtTeacherResult) {
        String logInfo = this.getClass().getName() + ":out:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            String token = tdNtTeacherResult.getToken();
            tdNtTeacherResult.setToken(CommonUtil.getToken());
            tdNtTeacherDao.updateTdNtTeacherPsdAndToken(tdNtTeacherResult);
            TdNtTeacherState tdNtTeacherState = new TdNtTeacherState();
            tdNtTeacherState.setTea_id(tdNtTeacherResult.getTea_id());
            tdNtTeacherState.setState(Constants.Teacher.State.offline);
            tdNtTeacherState.setState_order(Constants.Teacher.StateOrder.offline);
            tdNtTeacherDao.updateTdNtTeacherState(tdNtTeacherState);
            MemcachedUtils.delete(token);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("退出成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo loginNew(TdNtTeacherLogin tdNtTeacherLogin) {
        String logInfo = this.getClass().getName() + ":loginNew:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            TdNtTeacherResult tdNtTeacherResult = tdNtTeacherDao.findTdNtTeacherResult(tdNtTeacherLogin.getTea_email());
            if (tdNtTeacherResult != null) {
                if (tdNtTeacherResult.getTea_password().equals(MD5.code(tdNtTeacherLogin.getTea_password()))) {
                    if (!tdNtTeacherResult.getTea_islock().equals("0")) {
                        String token = tdNtTeacherResult.getToken();
                        tdNtTeacherResult.setToken(CommonUtil.getToken());
                        tdNtTeacherResult.setEqu_type(tdNtTeacherLogin.getEqu_type());
                        tdNtTeacherResult.setEqu_client_id(tdNtTeacherLogin.getEqu_client_id());

                        tdNtTeacherDao.updateTdNtTeacherPsdAndToken(tdNtTeacherResult);
                        MemcachedUtils.add(tdNtTeacherResult.getToken(), tdNtTeacherResult, 20 * 24 * 60 * 60);
                        MemcachedUtils.delete(token);
                        Map<String, Object> map = new HashMap<>();
                        map.put("token", tdNtTeacherResult.getToken());
                        map.put("lock", tdNtTeacherResult.getTea_islock());
                        retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                        retInfo.setTip(ValidationMessages.getValue("TEACHER.LOGIN.SUCCESS"));
                        retInfo.setObj(map);
                    } else {
                        retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                        retInfo.setTip(ValidationMessages.getValue("TEACHER.LOGIN.LOCK"));
                    }

                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("TEACHER.PSD.ERROR"));
                }

            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("TEACHER.LOGIN.NULL"));
            }
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo loginTWO(TdNtTeacherLogin loginUser, int version, String ip) {
        String logInfo = this.getClass().getName() + ":loginTWO:";
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();
        TokenResult tokenResult = null;

        try {
            TdNtTeacherResult tdNtTeacherResult = tdNtTeacherDao.findTdNtTeacherResult(loginUser.getTea_email());
            String appKey = rongCloudConfig.getAppkey();
            String appSecret = rongCloudConfig.getSecret();

            // 记录登录日志
            TdNtUserLoginLog tdNtUserLoginLog = new TdNtUserLoginLog();
            tdNtUserLoginLog.setUser_type(Integer.parseInt(Constants.user_type_teacher));
            tdNtUserLoginLog.setYyyymm(CommonUtil.getMonth(now));
            tdNtUserLoginLog.setLogin_ip(ip);
            tdNtUserLoginLog.setAccount(loginUser.getTea_email());//登录账号
            if (tdNtTeacherResult != null) {

                // 记录登录日志
                tdNtUserLoginLog.setUser_id(tdNtTeacherResult.getTea_id());
                tdNtUserLoginLog.setEqu_client_id(tdNtTeacherResult.getEqu_client_id() + "||" + loginUser.getEqu_client_id());//设备标识
                tdNtUserLoginLog.setEqu_type(tdNtTeacherResult.getEqu_type());//设备类型
                tdNtUserLoginLog.setOld_token(tdNtTeacherResult.getToken());
                tdNtUserLoginLog.setUid(tdNtTeacherResult.getUid());
                if (tdNtTeacherResult.getTea_password().equals(MD5.code(loginUser.getTea_password()))) {
                    if (!tdNtTeacherResult.getTea_islock().equals("0")) {
                        String token = tdNtTeacherResult.getToken();
                        tdNtTeacherResult.setToken(CommonUtil.getToken());
                        tdNtTeacherResult.setEqu_type(loginUser.getEqu_type());
                        //如客户端带过来设备id，则更新该字段，否则不更新
                        if (!Constants.default_equ_id.equals(loginUser.getEqu_client_id())) {
                            tdNtTeacherResult.setEqu_client_id(loginUser.getEqu_client_id());
                        }

                        tdNtTeacherDao.updateTdNtTeacherPsdAndToken(tdNtTeacherResult);
                        MemcachedUtils.add(tdNtTeacherResult.getToken(), tdNtTeacherResult, 20 * 24 * 60 * 60);
                        MemcachedUtils.delete(token);
                        Map<String, Object> map = new HashMap<>();
                        if (StringUtils.isBlank(tdNtTeacherResult.getRongcloud_token())) {
                            // 获取融云 Token 方法
                            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
                            String memb_id = "teacher" + tdNtTeacherResult.getTea_id();
                            String memb_head_portraituri = CommonUtil.getFullUri(tdNtTeacherResult.getTea_head_portrait());
                            tokenResult = rongCloud.user.getToken(memb_id, tdNtTeacherResult.getTea_name(), memb_head_portraituri);
                            tdNtTeacherDao.updateTeachersRongCloudToken(tokenResult.token, Integer.valueOf(tdNtTeacherResult.getTea_id()));
                            if (tokenResult.getToken() != null && tokenResult.getToken() != "") {
                                map.put("rongCloudToken", tokenResult.getToken());
                            }
                            logger.info("\nrongCloudToken-->" + tokenResult.toString());
                        } else {
                            map.put("rongCloudToken", tdNtTeacherResult.getRongcloud_token());
                        }
                        map.put("token", tdNtTeacherResult.getToken());
                        map.put("sig", tls_sigature.getUsersig(Constants.teacher + tdNtTeacherResult.getTea_id()));
                        map.put("lock", tdNtTeacherResult.getTea_islock());
                        map.put("Identifier", Constants.teacher + tdNtTeacherResult.getTea_id());
                        map.put("tea_id", tdNtTeacherResult.getTea_id());
                        map.put("uid", tdNtTeacherResult.getUid());
                        retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                        retInfo.setTip(ValidationMessages.getValue("TEACHER.LOGIN.SUCCESS"));
                        retInfo.setObj(map);
                        tdNtUserLoginLog.setIs_success("0");
                        tdNtUserLoginLog.setLogin_failer_desc("登录成功" + loginUser.getTea_password());
                    } else {
                        retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                        retInfo.setTip(ValidationMessages.getValue("TEACHER.LOGIN.LOCK"));
                        tdNtUserLoginLog.setIs_success("1");
                        tdNtUserLoginLog.setLogin_failer_desc("账号被锁定" + loginUser.getTea_password());
                    }
                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("TEACHER.PSD.ERROR"));
                    tdNtUserLoginLog.setIs_success("1");
                    tdNtUserLoginLog.setLogin_failer_desc("密码错误" + loginUser.getTea_password());
                }
            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("TEACHER.LOGIN.NULL"));
                tdNtUserLoginLog.setIs_success("1");
                tdNtUserLoginLog.setLogin_failer_desc("账号不存在，email:" + loginUser.getTea_email());
            }
            tdNtUserLoginLogDao.insertTdNtUserLoginLog(tdNtUserLoginLog);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    /**
     * 更新deviceId
     *
     * @param tea_id
     * @param equ_client_id
     * @return
     */
    public RetInfo updateEquClientId(int tea_id, String equ_client_id, String equ_type) {
        RetInfo retInfo = new RetInfo();
        if (equ_client_id == null || "".equals(equ_client_id.trim())) {
            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
            retInfo.setTip("无效参数：equ_client_id不能为空");
            return retInfo;
        } else if (equ_type == null || "".equals(equ_type.trim())) {
            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
            retInfo.setTip("无效参数：equ_type不能为空");
            return retInfo;
        }

        try {
            //更新数据库
            tdNtTeacherDao.updateEquClientIdByTeaId(tea_id, equ_client_id, equ_type);
            //更新缓存
            TdNtTeacherResult tdNtTeacher = tdNtTeacherDao.findTeacherByTeaId(tea_id);
            tdNtTeacher.setEqu_client_id(equ_client_id);
            tdNtTeacher.setEqu_type(equ_type);
            MemcachedUtils.replace(tdNtTeacher.getToken(), tdNtTeacher, 20 * 24 * 60 * 60);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("更新DeviceToken成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        return retInfo;
    }

    public String receiveRongCloudTokenForTeacher(Integer tea_id) {
        try {
            TdNtTeacher teacher = tdNtTeacherDao.findTeacherById(tea_id);
            String appKey = rongCloudConfig.getAppkey();
            String appSecret = rongCloudConfig.getSecret();
            Map<String, Object> map = new HashMap<>();
            // 获取融云 Token 方法
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            String ront_tea_id = "teacher" + teacher.getTea_id();
            String head_portrait = CommonUtil.getFullUri(teacher.getTea_head_portrait());
            TokenResult tokenResult = rongCloud.user.getToken(ront_tea_id, teacher.getTea_name(), head_portrait);
            tdNtTeacherDao.updateTeachersRongCloudToken(tokenResult.token, teacher.getTea_id());
            if (tokenResult.getToken() != null && tokenResult.getToken() != "") {
                return tokenResult.getToken();
            } else {
                throw new RuntimeException("获取融云token异常：" + tokenResult.errorMessage);
            }
        } catch (Exception e) {
            logger.error("获取融云token异常", e);
            throw new RuntimeException("获取融云token异常");
        }
    }
}
